$(function () {
    $("#sysRoleGrid").Grid({
        url: '../sys/role/list',
        colModel: [
            {label: '角色ID', name: 'id', index: "id", key: true, hidden: true},
            {label: '角色名称', name: 'roleName', index: "role_id", width: 75},
            {label: '所属公司', name: 'companyName', index: "company_id", width: 75},
            {label: '备注', name: 'remark', width: 100},
            {
                label: '创建时间', name: 'createTime', index: "create_time", width: 80, formatter: function (value) {
                return transDate(value);
            }
            }
        ]
    });
    vm.getProjectList();
});

//菜单树
var menu_ztree;
var menu_setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    },
    check: {
        enable: true,
        nocheckInherit: true
    }
};

//部门结构树
var dept_ztree;
var dept_setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    }
};

//数据树
var data_ztree;
var data_setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: "0"
        },
        key: {
            url: "nourl"
        }
    },
    check: {
        enable: true,
        nocheckInherit: true,
        chkboxType: {"Y": "", "N": ""}
    }
};


var vm = new Vue({
    el: '#sysRole',
    data: {
        q: {
            roleName: null,companyName:null
        },
        showList: true,
        title: null,
        appList: [],
        role: {companyId: '', companyName: ''},
        ruleValidate: {
            roleName: [
                {required: true, message: '角色名称不能为空', trigger: 'blur'}
            ],
            companyId: [
               {required: true, message: '所属公司不能为空', trigger: 'blur'}
            ]
        }
    },
    methods: {
    	selectCompany:function(){
			openWindow({
            	type: 2,
                title: "选择公司",
                area: ['80%', '60%'],
                content: ['../org/companyinfoSelect.html?status=1'],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                	var selectRowData = window[layero.find('iframe')[0]['name']].getSelectedRowData('#companyInfoGrid');
                	vm.role.companyId=selectRowData.id;
                	vm.role.companyName=selectRowData.name;
                	
                	vm.getDataTree(vm.role.companyId);
                    layer.close(index);
                }
            });
    	},
    	selectCompanyCopy:function(){
    		var roleIds = getSelectedRows("#sysRoleGrid");
			if(!roleIds){
				alert("选择的角色不能为空！");return;
			}
    		openWindow({
    			type: 2,
    			title: "选择公司",
    			area: ['80%', '60%'],
    			content: ['../org/companyinfoSelect.html'],
    			btn: ['确定', '取消'],
    			btn1: function (index,layero) {
    				var selectRowData = window[layero.find('iframe')[0]['name']].getSelectedRowData('#companyInfoGrid');
    				var companyId=selectRowData.id;
    				var companyName=selectRowData.name;
    				if(!companyId){
    					alert("选择的公司不能为空！");return;
    				}
    				layer.close(index);
    				confirm('确定要复制选中的角色到【'+companyName+'】？', function () {
    	                Ajax.request({
    	                    url: "../sys/role/copy?companyId="+companyId,
    	                    params: JSON.stringify(roleIds),
    	                    contentType: "application/json",
    	                    type: 'POST',
    	                    successCallback: function () {
    	                        alert('操作成功', function (index) {
    	                            vm.reload();
    	                        });
    	                    }
    	                });
    	            });
    			}
    		});
    	},
    	changeApp:function(data){
    		for (var i = 0; i < vm.appList.length; i++) {
    			if(data.indexOf(vm.appList[i].id)> -1){
    				if(!vm.appList[i].selectStatus){
    					vm.appList[i].selectStatus=1;
    					vm.getMenuTreeByProject(vm.appList[i].id);
    				}
    			}else{
    				vm.appList[i].selectStatus=0;
    			}
			}
    	},
    	getProjectList: function () {
        	//加载部门树
        	Ajax.request({
        		url: "../sys/domain/queryAllByNoConditions",
        		async: true,
        		successCallback: function (r) {
        			vm.appList=r.list;
        		}
        	});
        },
        query: function () {
        	$("#sysRoleGrid").jqGrid('setGridParam',{page:1});
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.role = {companyId: '', companyName: ''};
            //vm.getMenuTree(null);
            for (var i = 0; i < vm.appList.length; i++) {
    			vm.appList[i].selectStatus=0;
			}
//            vm.getDept();
            vm.getDataTree();
        },
        update: function () {
            var roleId = getSelectedRow("#sysRoleGrid");
            if (roleId == null) {
                return;
            }
            for (var i = 0; i < vm.appList.length; i++) {
    			vm.appList[i].selectStatus=0;
			}
            vm.showList = false;
            vm.title = "修改";
            vm.getDataTree();
            //vm.getMenuTree(roleId);
            vm.getRole(roleId);
        },
        del: function (event) {
            var roleIds = getSelectedRows("#sysRoleGrid");
            if (roleIds == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../sys/role/delete",
                    params: JSON.stringify(roleIds),
                    contentType: "application/json",
                    type: 'POST',
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getRole: function (roleId) {
            Ajax.request({
                url: "../sys/role/info/" + roleId,
                async: true,
                successCallback: function (r) {
                    vm.role = r.role;
//                    vm.getDept();

                    //勾选角色所拥有的菜单
                    vm.changeApp(vm.role.domainIdList);
                    vm.getDataTree(vm.role.companyId);
                }
            });
        },
        saveOrUpdate: function (event) {
            //获取选择的菜单
            var menuIdList = new Array();
            if(vm.appList){
            	for (var i = 0; i < vm.appList.length; i++) {
            		if(vm.appList[i].selectStatus){
            			var ztreeObj = $.fn.zTree.getZTreeObj("menuTree_"+vm.appList[i].id);
            			
            			var nodes = ztreeObj.getCheckedNodes(true);
//            			var nodes = ztreeObj.getSelectedNodes();
            			for (var j = 0; j < nodes.length; j++) {
            				menuIdList.push(nodes[j].id);
            			}
            		}
            	}
            }
            vm.role.menuIdList = menuIdList;
            //获取选择的数据
            var nodes = data_ztree.getCheckedNodes(true);
            var deptIdList = new Array();
            for (var i = 0; i < nodes.length; i++) {
                deptIdList.push(nodes[i].id);
            }
            vm.role.deptIdList = deptIdList;

            var url = vm.role.id == null ? "../sys/role/save" : "../sys/role/update";
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.role),
                contentType: "application/json",
                type: 'POST',
                successCallback: function () {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        getMenuTreeByProject: function (projectId) {
        	//加载菜单树
        	Ajax.request({
        		url: "../sys/menu/menuList?domainId="+projectId,
        		async: true,
        		successCallback: function (r) {
        			if(r.menuList.length<=0){
        				$("#menuTree_"+projectId).html("该项目工程没有功能菜单！");
        			}else{
        				var projectmenuTree=$.fn.zTree.init($("#menuTree_"+projectId), menu_setting, r.menuList);
        				projectmenuTree.expandAll(false);
//        				treeObj.checkAllNodes(false);
        				
        				if(vm.role.id){
        					var menuIdList=vm.role.menuIdList;
        					if(menuIdList&&menuIdList.length>0){
        						for (var i = 0; i < menuIdList.length; i++) {
        							var nodes=projectmenuTree.getNodesByParam("id",menuIdList[i],null);
        							if(nodes&&nodes.length>0){
        								projectmenuTree.checkNode(nodes[0], true, false);
        							}
								}
        					}
        				}
        			}
        		}
        	});
        },
        getDataTree: function (parentList) {
        	var paramParentList="";
        	if(parentList){
        		paramParentList="?parentList="+parentList;
        	}
            //加载菜单树
            Ajax.request({
                url: "../org/architecture/queryAll"+paramParentList,
                async: true,
                successCallback: function (r) {
                    data_ztree = $.fn.zTree.init($("#dataTree"), data_setting, r.list);
                    //展开所有节点
                    data_ztree.expandAll(true);

                    if(vm.role.id){
                    	var deptIds = vm.role.deptIdList;
                    	for (var i = 0; i < deptIds.length; i++) {
                    		var nodes=data_ztree.getNodesByParam("id",deptIds[i],null);
                    		if(nodes&&nodes.length>0){
                    			data_ztree.checkNode(nodes[0], true, false);
                    		}
						}
                    }
                }
            });
        },
        getDept: function () {
            //加载部门树
            Ajax.request({
                url: "../org/company/select",
                async: true,
                successCallback: function (r) {
                    dept_ztree = $.fn.zTree.init($("#sysRoleTree"), dept_setting, r.deptList);
                    dept_ztree.expandAll(true);
                }
            });
        },
        selectDeptTree: function () {
            openWindow({
                title: "选择公司",
                area: ['300px', '450px'],
                content: jQuery("#sysRoleLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = dept_ztree.getSelectedNodes();
                    //选择上级部门
                    vm.role.deptId = node[0].deptId;
                    vm.role.deptName = node[0].name;
                    layer.close(index);
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#sysRoleGrid").jqGrid('getGridParam', 'page');
            $("#sysRoleGrid").jqGrid('setGridParam', {
                postData: {'roleName': vm.q.roleName,'companyName': vm.q.companyName},
                page: 1
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
        	$("#sysRoleGrid").jqGrid('setGridParam',{page:1});
            vm.q = {
                roleName: '',companyName:''
            }
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
    }
});